import { axisColorConfig } from '@/config/stage-canvas-config';
import { LockOutlined } from '@ant-design/icons';
import {
  ProForm,
  ProFormDependency,
  ProFormDigit,
  ProFormList,
  ProFormSegmented,
} from '@ant-design/pro-components';
import { Col, GetProp, Row, Space } from 'antd';
import { get, isUndefined, transform } from 'lodash-es';
import { ReactNode, useRef } from 'react';
import { Basis } from '../constants';
import { Axis } from '../types';
import { AxisBackup } from '../AxisBackup';
import { FormTitle } from '../CustomForm';
import { useModel } from 'umi';

export const PlankEditor = () => (
  <>
    <ProFormDependency name={[['plank', 'isRectPlank']]}>
      {(values) => {
        const isRectPlank = get(values, ['plank', 'isRectPlank']);

        return <>{isRectPlank ? <RectPlankEditor /> : <NoRectPlankEditor />}</>;
      }}
    </ProFormDependency>
  </>
);

function Lock({ text, showLock }: { text?: ReactNode; showLock?: boolean }) {
  return (
    <div>
      {showLock && <LockOutlined />}
      {text}
    </div>
  );
}

function LockSegmented(props: {
  name: GetProp<typeof ProFormSegmented, 'name'>;
  valueEnum: Record<string, ReactNode>;
}) {
  const { name, valueEnum } = props;

  return (
    <ProFormDependency name={[name]}>
      {(values) => {
        const currentValue = get(values, name);
        return (
          <ProFormSegmented
            fieldProps={{ size: 'small' }}
            noStyle
            name={name}
            valueEnum={transform(
              valueEnum,
              (result, value, key) => {
                result[key] = (
                  <Lock text={value} showLock={currentValue === key} />
                );
              },
              {} as Record<string, ReactNode>,
            )}
          />
        );
      }}
    </ProFormDependency>
  );
}

const formItemLayoutProps = { labelCol: { span: 8 } };
function RectPlankEditor() {
  const { setShowBasis } = useModel('StageCanvas');

  function createFieldProps(axis: Axis) {
    return {
      onPointerOver: () => setShowBasis({ [axis]: true }),
      onPointerLeave: () => setShowBasis({ [axis]: false }),
    };
  }

  return (
    <>
      <FormTitle title="板件尺寸" />
      <ProForm.Group>
        <ProForm.Item
          {...formItemLayoutProps}
          label={
            <span className="text-secondary">
              宽度<span style={{ color: axisColorConfig.x }}>(X)</span>
            </span>
          }
        >
          <Space>
            <LockSegmented
              name={['plank', 'basis', 'y']}
              valueEnum={{
                [Basis.Left]: '左',
                [Basis.Right]: '右',
              }}
            />
            <ProFormDigit
              noStyle
              name={['plank', 'size', 'length']}
              fieldProps={createFieldProps(Axis.y)}
            />
          </Space>
        </ProForm.Item>
        <ProForm.Item
          {...formItemLayoutProps}
          label={
            <span className="text-secondary">
              深度<span style={{ color: axisColorConfig.y }}>(Y)</span>
            </span>
          }
        >
          <Space>
            <LockSegmented
              name={['plank', 'basis', 'x']}
              valueEnum={{
                [Basis.Front]: '前',
                [Basis.Back]: '后',
              }}
            />
            <ProFormDigit
              noStyle
              name={['plank', 'size', 'width']}
              fieldProps={createFieldProps(Axis.x)}
            />
          </Space>
        </ProForm.Item>
        <ProForm.Item
          className="mb-0"
          {...formItemLayoutProps}
          label={
            <span className="text-secondary">
              高度<span style={{ color: axisColorConfig.z }}>(Z)</span>
            </span>
          }
        >
          <Space>
            <div style={{ width: 74 }}>&nbsp;</div>
            <ProFormDigit
              noStyle
              disabled
              name={['plank', 'size', 'thickness']}
            />
          </Space>
        </ProForm.Item>
      </ProForm.Group>
    </>
  );
}
function NoRectPlankEditor() {
  const { setHighlightProfilePoint } = useModel('StageCanvas');
  const foucsIndexRef = useRef<number>();
  function createFieldProps(i: number) {
    return {
      onFocus: () => {
        foucsIndexRef.current = i;
        setHighlightProfilePoint(i);
      },
      onBlur: () => {
        foucsIndexRef.current = undefined;
        setHighlightProfilePoint(undefined);
      },
      onPointerOver: () => {
        setHighlightProfilePoint(i);
      },
      onPointerLeave: () => {
        if (foucsIndexRef.current === undefined) {
          setHighlightProfilePoint(undefined);
        }
      },
    };
  }
  return (
    <>
      <ProFormDependency
        name={[
          ['plank', 'points'],
          ['plank', 'size', 'thickness'],
        ]}
      >
        {(values) => {
          const points = get(values, ['plank', 'points']);
          const thickness = get(values, ['plank', 'size', 'thickness']);
          return (
            <>
              {/* <div>
                板件轮廓 共 {points.length} 个轮廓点 板高：{thickness}
              </div> */}
              <FormTitle title="板件轮廓" />
            </>
          );
        }}
      </ProFormDependency>

      <ProFormList
        name={['plank', 'points']}
        creatorButtonProps={false}
        actionRender={() => []}
        colProps={{ span: 24 }}
      >
        {(_, i) => {
          const order = i + 1;
          const title = (
            <Row style={{ textAlign: 'center' }}>
              <Col offset={8} span={8}>
                横轴
                <AxisBackup axis={Axis.x} parentheses />
              </Col>
              <Col span={8}>
                纵轴
                <AxisBackup axis={Axis.y} parentheses />
              </Col>
            </Row>
          );
          return (
            <>
              {/* {order === 1 && title} */}
              <ProForm.Group grid colProps={{ span: 24 }}>
                <Col span={8}>
                  <span className="text-secondary">点{order}</span>
                </Col>
                <Col span={16}>
                  <ProForm.Item>
                    <Space.Compact>
                      <ProFormDigit
                        noStyle
                        min={Number.MIN_SAFE_INTEGER}
                        name={['x']}
                        fieldProps={{
                          prefix: <AxisBackup axis={Axis.x} />,
                          ...createFieldProps(i),
                        }}
                      />
                      <ProFormDigit
                        noStyle
                        min={Number.MIN_SAFE_INTEGER}
                        name={['y']}
                        fieldProps={{
                          prefix: <AxisBackup axis={Axis.y} />,
                          ...createFieldProps(i),
                        }}
                      />
                    </Space.Compact>
                  </ProForm.Item>
                </Col>
              </ProForm.Group>
              {/* <ProForm.Group>
                <span>点{order}</span>
                <ProFormDigit
                  min={Number.MIN_SAFE_INTEGER}
                  name={['x']}
                />
                <ProFormDigit
                  min={Number.MIN_SAFE_INTEGER}
                  name={['y']}
                />
              </ProForm.Group> */}
            </>
          );
        }}
      </ProFormList>
    </>
  );
}
